<?php

namespace app\admin\controller\mall;

use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\model\MallCate;
use app\common\model\MallGoods;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
/**
 * Class Applygoods
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="审核商品管理")
 */
class Applygoods extends AdminController
{
    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model =(new MallGoods());
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index($id='')
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where[] =[['apply_status','in',[0,2]]];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order('sort desc,id desc')
                ->select();
            foreach ($list as $k=>$v){
                $catinfo =(new MallCate())->where([['id','=',$v['cate_id']]])->find();
                $list[$k]['catename'] =!empty($catinfo)?$catinfo['title']:'';
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('mid',$id);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="审核入库")
     */
    public function stock($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post['total_stock'] = $row->total_stock + $post['stock'];
                $post['stock'] = $row->stock + $post['stock'];
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        $this->assign('mid',0);
        return $this->fetch();
    }
}